package com.rocksea.app.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.Request;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.rocksea.app.R;
import com.rocksea.app.UploadingTask;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.image.ImageTable;
import com.rocksea.app.dialog.CustomBottomSheetDialog;
import com.rocksea.app.entry.ImageInfo;
import com.rocksea.app.entry.InspectionForm;
import com.rocksea.app.http.HttpUtil;
import com.rocksea.app.utils.PerUtils;
import com.rocksea.app.utils.UiUtils;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.galleryfinal.widget.GFImageView;

/**
 * Created by 吴志华 on 2017/10/16.
 *
 */

public class PhotoActivity extends AppCompatActivity
{
    public static final String PHOTO_INTENT = "com.rocksea.app.photoIntent";
    public static final String PLAN_INTENT = "com.rocksea.app.PLAN";

    private static final int CONFING_TIME = 0;
    private static final int CONFING_TEST_TYPE = 1;
    private static final int CONFING_TYPE = 2;
    private static final int CONFING_PLAN_NUM = 3;
    private static final int CONFING_PILE_NO = 4;
    private static final int CONFING_REMAKE = 5;

    private static final int GALLERYFINAL_CODE = 8;
    private static final int GALLERYFINAL_CAMERA_CODE = 9;

    private ArrayList<String> photoInfos;

    private ImageInfo imageInfo;
    private InfoAdapter infoAdapter;
    private InspectionForm.InspectionFormListBean mInspectionForm;
    private ImageView pilePhoto;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_dialog_layout);
        initGalleryFinal();
        imageInfo = new ImageInfo();
        photoInfos = new ArrayList<>();

        mInspectionForm = getIntent().getParcelableExtra(PHOTO_INTENT);

        photoInfos.add(CONFING_TIME, PerUtils.dateToStr(new Date()));
        switch (mInspectionForm.applyMethod)
        {
            case "4":
                photoInfos.add(CONFING_TEST_TYPE, "静载");
                break;
            case "2":
                photoInfos.add(CONFING_TEST_TYPE, "高应变");
                break;
            case "1":
                photoInfos.add(CONFING_TEST_TYPE, "低应变");
                break;
            default:
                photoInfos.add(CONFING_TEST_TYPE, "声波");
                break;
        }

        int planMode = getIntent().getIntExtra(PLAN_INTENT,0);
        if (planMode == 0)
        {
            photoInfos.add(CONFING_TYPE,"桥梁");
        }
        else
        {
            photoInfos.add(CONFING_TYPE,"路隧");
        }
        photoInfos.add(CONFING_PLAN_NUM,mInspectionForm.number);
        photoInfos.add(CONFING_PILE_NO,"请选择桩号");
        photoInfos.add(CONFING_REMAKE,"请输入");

        initViews();

        showSheetDialog();
    }

    private void initViews()
    {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
        {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
            actionBar.setTitle("拍摄现场照片");
        }

        pilePhoto = (ImageView) findViewById(R.id.Photo_View);
        pilePhoto.setOnClickListener(onClickListener);

        ListView infoList = (ListView) findViewById(R.id.Info_List);
        infoAdapter = new InfoAdapter(this);
        infoList.setAdapter(infoAdapter);
        infoList.setOnItemClickListener(onItemClickListener);
    }

    public void saveImage(View view)
    {
        if (mInspectionForm == null)
            return;

        if (photoInfos.get(CONFING_PILE_NO).equals("请选择桩号"))
        {
            UiUtils.showToast("请选择桩号");
            return;
        }

        imageInfo.setPlanNum(photoInfos.get(CONFING_PLAN_NUM));
        imageInfo.setPileNo(photoInfos.get(CONFING_PILE_NO));
        imageInfo.setRemake(photoInfos.get(CONFING_REMAKE));
        imageInfo.setTime(photoInfos.get(CONFING_TIME));

        switch (photoInfos.get(CONFING_TEST_TYPE))
        {
            case "低应变":
                imageInfo.setTestType(1);
                break;
            case "高应变":
                imageInfo.setTestType(2);
                break;
            case "声波":
                imageInfo.setTestType(3);
                break;
            case "静载":
                imageInfo.setTestType(4);
                break;
        }

        ImageTable imageTable = new ImageTable(imageInfo);
        DbCenter.mImageDbHelper.insert(imageTable);

        if (HttpUtil.isImageAutoUpload())
        {
            UploadingTask.uploadImage(imageTable);
        }
        UiUtils.showToast("保存成功");
    }

    public void cancel(View view)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("确定取消吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });
        builder.setCancelable(true);
        builder.show();
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private AdapterView.OnClickListener onClickListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            showSheetDialog();
        }
    };


    private void showSheetDialog()
    {
        CustomBottomSheetDialog customBottomSheetDialog = new CustomBottomSheetDialog(PhotoActivity.this,onBottomSheetDialogListener);
        customBottomSheetDialog.showDialog();
    }


    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            switch (position)
            {
                case CONFING_TIME:
                    UiUtils.showToast("暂不支持修正时间");
                    break;
                case CONFING_TYPE:
                case CONFING_PLAN_NUM:
                    break;
                case CONFING_PILE_NO:
                    //判断是桥梁还是路隧
                    //桥梁提供用户选择桩号 路隧的话提供用户输入桩号
                    if (photoInfos.get(CONFING_TYPE).equals("桥梁"))
                    {
                        ArrayList<String> pileNos = new ArrayList<>();
                        for (InspectionForm.PileBean pileBean : mInspectionForm.pileList)
                        {
                            pileNos.add(pileBean.pileNo);
                        }
                        showChooseDialog(CONFING_PILE_NO,pileNos);
                    }
                    else
                    {
                        showInputDialog(CONFING_PILE_NO);
                    }

                    break;
                case CONFING_REMAKE:
                    showChooseDialog(CONFING_REMAKE,null);
                    break;
            }
        }
    };

    private void showChooseDialog(final int confingType, ArrayList<String> chooseItem)
    {
        if (confingType != CONFING_REMAKE)
        {
            final String[] chooseItemArray = new String[chooseItem.size()];
            for (int i = 0; i < chooseItem.size(); i++)
            {
                chooseItemArray[i] = chooseItem.get(i);
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(PhotoActivity.this);
            int defaultWhich = -1;
            switch (confingType)
            {
                case CONFING_PILE_NO:
                    builder.setTitle("选择桩号");
                    for (int i = 0; i < chooseItemArray.length; i++)
                        if (photoInfos.get(CONFING_PILE_NO).equals( chooseItemArray[i]))
                            defaultWhich = i;
                    break;
            }
            builder.setSingleChoiceItems(chooseItemArray,defaultWhich, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.dismiss();
                    switch (confingType)
                    {
                        case CONFING_PILE_NO:
                            photoInfos.remove(CONFING_PILE_NO);
                            photoInfos.add(CONFING_PILE_NO,chooseItemArray[which]);
                            for (InspectionForm.PileBean pileBean : mInspectionForm.pileList)
                            {
                                if (pileBean.pileNo.equals(chooseItemArray[which]))
                                    imageInfo.setPileId(mInspectionForm.id);
                            }
                            break;

                        default:
                            break;
                    }
                    infoAdapter.notifyDataSetChanged();
                }
            });
            builder.show();
        }

        else
            showInputDialog(CONFING_REMAKE);
    }

    private void showKeyBroad(final View view)
    {
        getWindow().getDecorView().postDelayed(new Runnable(){
            @Override
            public void run() {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager!=null)
                    inputMethodManager.showSoftInput(view,0);
            }
        },60);
    }

    private class InfoAdapter extends BaseAdapter
    {

        private Context context;

        private InfoAdapter(Context context)
        {
            this.context = context;
        }
        @Override
        public int getCount()
        {
            return 6;
        }

        @Override
        public Object getItem(int position)
        {
            return null;
        }

        @Override
        public long getItemId(int position)
        {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView==null)
                convertView = View.inflate(context,R.layout.info_item_layout,null);
            TextView mInfoTitle = (TextView) convertView.findViewById(R.id.Info_Title);
            TextView mInfoContent = (TextView) convertView.findViewById(R.id.Info_Content);
            switch (position)
            {
                case CONFING_TIME:
                    mInfoTitle.setText("拍摄时间");
                    mInfoContent.setText(photoInfos.get(CONFING_TIME));
                    break;
                case CONFING_TEST_TYPE:
                    mInfoTitle.setText("实验类型");
                    mInfoContent.setText(photoInfos.get(CONFING_TEST_TYPE));
                    break;
                case CONFING_TYPE:
                    mInfoTitle.setText("报检单类型");
                    mInfoContent.setText(photoInfos.get(CONFING_TYPE));
                    break;
                case CONFING_PLAN_NUM:
                    mInfoTitle.setText("报检单编号");
                    mInfoContent.setText(photoInfos.get(CONFING_PLAN_NUM));
                    break;
                case CONFING_PILE_NO:
                    mInfoTitle.setText("桩号");
                    mInfoContent.setText(photoInfos.get(CONFING_PILE_NO));
                    break;
                case CONFING_REMAKE:
                    mInfoTitle.setText("照片说明");
                    mInfoContent.setText(photoInfos.get(CONFING_REMAKE));
                    break;
            }
            return convertView;
        }
    }

    public void initGalleryFinal()
    {
        //配置主题
        //ThemeConfig.CYAN
        ThemeConfig theme = new ThemeConfig.Builder().setTitleBarBgColor(ContextCompat.getColor(this,R.color.colorPrimary))
        .build();
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(false)
                .setEnableCrop(false)
                .setEnableRotate(false)
                .setCropSquare(false)
                .setEnablePreview(true).build();

        //配置imageloader
        ImageLoader imageloader = new UILImageLoader();
        //设置核心配置信息
        CoreConfig coreConfig = new CoreConfig.Builder(this, imageloader, theme)
                .setFunctionConfig(functionConfig)
        .build();
        GalleryFinal.init(coreConfig);
    }

    private CustomBottomSheetDialog.OnBottomSheetDialogListener onBottomSheetDialogListener = new CustomBottomSheetDialog.OnBottomSheetDialogListener()
    {
        @Override
        public void onTakePhoto()
        {

            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            startActivityForResult(intent,GALLERYFINAL_CAMERA_CODE);
        }

        @Override
        public void onPhotoALbum()
        {
            GalleryFinal.openGallerySingle(GALLERYFINAL_CODE,mOnHanlderResultCallback);
        }
    };

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback()
    {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList)
        {
            System.out.println(reqeustCode);
            Bitmap newBitMap = BitmapFactory.decodeFile(resultList.get(0).getPhotoPath());
            Bitmap zipImage = Bitmap.createScaledBitmap(newBitMap,150,150,true);
            pilePhoto.setImageBitmap(zipImage);
            imageInfo.setBitmap(zipImage);
            photoInfos.remove(CONFING_TIME);
            photoInfos.add(CONFING_TIME,PerUtils.dateToStr(new Date()));
            photoInfos.remove(CONFING_REMAKE);
            photoInfos.add(CONFING_REMAKE,"请输入");
            infoAdapter.notifyDataSetChanged();
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg)
        {
            UiUtils.showToast(errorMsg);
        }
    };
    private class UILImageLoader implements ImageLoader
    {

        @Override
        public void displayImage(Activity activity, String path,final GFImageView imageView, Drawable defaultDrawable, int width, int height)
        {
            Glide.with(activity).load("file://" + path)
                .placeholder(defaultDrawable)
                .error(defaultDrawable)
                .override(width,height)
                .diskCacheStrategy(DiskCacheStrategy.NONE) //不缓存到SD卡
                .skipMemoryCache(true)
                //.centerCrop()
                .into(new ImageViewTarget<GlideDrawable>(imageView)
                {
                    @Override
                    protected void setResource(GlideDrawable resource)
                    {
                        imageView.setImageDrawable(resource);
                    }

                    @Override
                    public void setRequest(Request request)
                    {
                        imageView.setTag(R.id.Photo_View,request);
                    }

                    @Override
                    public Request getRequest()
                    {
                        return (Request) imageView.getTag(R.id.Photo_View);
                    }
                });
        }

        @Override
        public void clearMemoryCache()
        {

        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bitmap = null;
        if (data!=null) {
            switch (requestCode)
            {
                case GALLERYFINAL_CAMERA_CODE:
                    if (data.getData()!=null||data.getExtras()!=null)
                    {
                        Uri uri = data.getData();
                        if (uri!=null)
                            bitmap = BitmapFactory.decodeFile(uri.getPath());
                        if (bitmap==null)
                        {
                            Bundle bundle = data.getExtras();
                            if (bundle!=null)
                            {
                                bitmap = (Bitmap) bundle.get("data");
                                imageInfo.setBitmap(bitmap);
                                pilePhoto.setImageBitmap(bitmap);
                                photoInfos.remove(CONFING_TIME);
                                photoInfos.add(CONFING_TIME,PerUtils.dateToStr(new Date()));
                                photoInfos.remove(CONFING_REMAKE);
                                photoInfos.add(CONFING_REMAKE,"请输入");
                                infoAdapter.notifyDataSetChanged();
                            }
                            else
                                Log.e("onActivityResult: ","获取照片失败");
                        }
                    }
                    break;
            }
        }
    }


    public void showInputDialog(final int config)
    {
        RelativeLayout dialogLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.layout_input_text, new LinearLayout(this), false);
        final AutoCompleteTextView mInputCode = (AutoCompleteTextView) dialogLayout.findViewById(R.id.Machine_Code);
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if (config == CONFING_PILE_NO)
            builder.setTitle("请输入桩号");
        else
            builder.setTitle("请输入备注");
        builder.setView(dialogLayout);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                String newValue = mInputCode.getText().toString().trim();
                dialog.dismiss();
                photoInfos.remove(config);
                photoInfos.add(config,newValue);
                infoAdapter.notifyDataSetChanged();
            }
        });

        builder.setNegativeButton("取消", null);
        showKeyBroad(mInputCode);
        builder.show();
    }
}
